<template>
  <div class="cart">
    <div class="head">新用户下单立减5元</div>
    <div class="clearCar">
      <span>购物车</span>
      <span class="clear" @click="clearAll()">
        <van-icon name="delete-o" />清空购物车
      </span>
    </div>
    <ul class="ul">
      <li
        class="item"
        v-for="item in $store.getters.shopCartList"
        :key="item.id"
      >
        <p>{{ item.name }}</p>
        <span class="price">￥{{ (item.num * item.price).toFixed(2) }}</span>
        <p class="btn">
          <span
            class="reduce"
            v-show="item.num > 0 ? true : false"
            @click="addNum(item.id, (num = -1))"
            ><van-icon name="minus"
          /></span>
          <span class="num">{{ item.num }}</span>
          <span class="add" @click="addNum(item.id, (num = 1))"
            ><van-icon name="plus"
          /></span>
        </p>
      </li>
    </ul>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from "vue-property-decorator";

@Component
export default class extends Vue {
  addNum(id: number, num: number) {
    this.$store.commit("add", { id: id, num: num });
  }
  clearAll() {
    for (const obj of this.$store.state.orderInfo) {
      for (const child of obj.foods) {
        child.num = 0;
      }
    }
    this.$store.state.actionShow = false;
    this.$store.state.content = 0;
  }
  get getTotalPrice(): number {
    let total: number = 0;
    let a = this.$store.getters.shopCartList;
    for (const obj of a) {
      if (obj.num > 0) {
        total += obj.num * obj.price;
      }
    }
    return total;
  }
  @Watch("getTotalPrice")
  onGetTotalPriceChanged(val: number) {
    if (val == 0) {
      this.$store.state.actionShow = false;
    }
  }
}
</script>

<style lang="scss" scoped>
.cart {
  // overflow: hidden;
  padding-bottom: 60px;
  .head {
    line-height: 40px;
    width: 100%;
    background: #fee7c8;
    color: #f53a0b;
    text-align: center;
    font-size: 12px;
  }
  .clearCar {
    display: flex;
    width: 100%;
    padding: 10px;
    justify-content: space-between;
    align-items: center;
    .clear {
      font-size: 12px;
      color: rgba(0, 0, 0, 0.4);
      cursor: pointer;
    }
  }
  .item {
    padding: 10px;
    display: flex;
    p:first-child {
      flex: 1;
      font-weight: bold;
    }
    .price {
      width: 80px;
      color: #f53a0b;
    }
  }
}
.btn {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  .num {
    padding: 0 10px;
  }
  .reduce {
    border-radius: 50%;
    border: 1px solid #e7e7e7;
    width: 24px;
    height: 24px;
    background-color: transparent;
    font-size: 16px;
    text-align: center;
    line-height: 24px;
  }
  .add {
    border-radius: 50%;
    width: 24px;
    height: 24px;
    background-color: rgba(255, 195, 0);
    font-size: 16px;
    text-align: center;
    line-height: 24px;
  }
}
</style>